package com.cby.operation.common.widget

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import com.cby.operation.common.ext.dip2px

/**
 * Description:MaxHeightView  当前定制为UI设定的最大高度
 *
 * @author 陈宝阳
 * @create 2020/8/24 10:14
 */
class MaxHeightView : FrameLayout {

    /**
     * 优先级高
     */
    private val mMaxRatio = DEFAULT_MAX_RATIO

    /**
     * 优先级低
     */
    private var mMaxHeight = DEFAULT_MAX_HEIGHT

    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
        init(context)
    }

    private fun init(context: Context) {
        mMaxHeight = context.dip2px(340f).toFloat()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var heightSize = MeasureSpec.getSize(heightMeasureSpec)
        if (heightMode == MeasureSpec.EXACTLY) {
            heightSize = if (heightSize <= mMaxHeight) heightSize else mMaxHeight.toInt()
        }
        if (heightMode == MeasureSpec.UNSPECIFIED) {
            heightSize = if (heightSize <= mMaxHeight) heightSize else mMaxHeight.toInt()
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            heightSize = if (heightSize <= mMaxHeight) heightSize else mMaxHeight.toInt()
        }
        val maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize,
                heightMode)
        super.onMeasure(widthMeasureSpec, maxHeightMeasureSpec)
    }

    companion object {
        private const val DEFAULT_MAX_RATIO = 0.6f
        private const val DEFAULT_MAX_HEIGHT = 0f
    }
}